package com.teacher.game.framework.util;

import android.util.Log;
import com.teacher.game.model.Player;

/**
 * 下蹲机制增强工具类
 * 
 * 为Story 2.3提供额外的下蹲机制增强功能，包括：
 * - 连续下蹲检测和防抖
 * - 下蹲效果增强
 * - 下蹲性能统计
 * - 自适应下蹲时间
 * 
 * @version 1.0
 * @since 2025-09-12
 */
public class DuckingEnhancement {
    
    private static final String TAG = "DuckingEnhancement";
    
    // 防抖设置
    private static final float DUCK_DEBOUNCE_TIME = 0.2f; // 防抖时间200ms
    private float lastDuckTime = 0;
    
    // 性能统计
    private int duckCount = 0;
    private float totalDuckTime = 0;
    private long sessionStartTime = System.currentTimeMillis();
    
    // 自适应设置
    private boolean adaptiveDurationEnabled = false;
    private float playerSkillFactor = 1.0f; // 玩家技能系数
    
    /**
     * 增强版下蹲处理
     * 
     * @param player 玩家对象
     * @param currentTime 当前游戏时间
     * @return 是否成功触发下蹲
     */
    public boolean enhancedDuck(Player player, float currentTime) {
        // 防抖检测
        if (currentTime - lastDuckTime < DUCK_DEBOUNCE_TIME) {
            Log.v(TAG, "下蹲防抖：忽略连续点击");
            return false;
        }
        
        // 检查是否可以下蹲
        if (player.isJumping()) {
            Log.v(TAG, "跳跃中无法下蹲");
            return false;
        }
        
        if (player.isDucking()) {
            Log.v(TAG, "已经在下蹲中");
            return false;
        }
        
        // 执行下蹲
        player.duck();
        lastDuckTime = currentTime;
        duckCount++;
        
        // 记录性能数据
        recordDuckingMetrics();
        
        Log.d(TAG, "成功触发下蹲 (总次数: " + duckCount + ")");
        return true;
    }
    
    /**
     * 记录下蹲性能指标
     */
    private void recordDuckingMetrics() {
        totalDuckTime += 1.0f; // 固定下蹲时间1秒
        
        // 每50次下蹲输出统计信息
        if (duckCount % 50 == 0) {
            printDuckingStats();
        }
    }
    
    /**
     * 打印下蹲统计信息
     */
    public void printDuckingStats() {
        long sessionDuration = System.currentTimeMillis() - sessionStartTime;
        float sessionMinutes = sessionDuration / 1000f / 60f;
        float ducksPerMinute = sessionMinutes > 0 ? duckCount / sessionMinutes : 0;
        
        Log.i(TAG, "========== 下蹲统计 ==========");
        Log.i(TAG, "总下蹲次数: " + duckCount);
        Log.i(TAG, "总下蹲时长: " + String.format("%.1f", totalDuckTime) + "秒");
        Log.i(TAG, "游戏时长: " + String.format("%.1f", sessionMinutes) + "分钟");
        Log.i(TAG, "下蹲频率: " + String.format("%.1f", ducksPerMinute) + "次/分钟");
        Log.i(TAG, "=============================");
    }
    
    /**
     * 启用自适应下蹲持续时间
     * 根据玩家表现调整下蹲时间
     * 
     * @param enabled 是否启用
     */
    public void enableAdaptiveDuration(boolean enabled) {
        this.adaptiveDurationEnabled = enabled;
        Log.i(TAG, "自适应下蹲持续时间: " + (enabled ? "启用" : "禁用"));
    }
    
    /**
     * 更新玩家技能系数
     * 基于玩家的游戏表现动态调整
     * 
     * @param skillFactor 技能系数 (0.5-2.0)
     */
    public void updatePlayerSkillFactor(float skillFactor) {
        this.playerSkillFactor = Math.max(0.5f, Math.min(2.0f, skillFactor));
        Log.d(TAG, "玩家技能系数更新: " + String.format("%.2f", this.playerSkillFactor));
    }
    
    /**
     * 获取建议的下蹲持续时间
     * 
     * @return 建议的持续时间（秒）
     */
    public float getRecommendedDuckDuration() {
        if (!adaptiveDurationEnabled) {
            return 1.0f; // 默认1秒
        }
        
        // 根据玩家技能调整：
        // 新手玩家(技能系数0.5) -> 1.5秒
        // 普通玩家(技能系数1.0) -> 1.0秒  
        // 高手玩家(技能系数2.0) -> 0.7秒
        float baseDuration = 1.0f;
        float adjustedDuration = baseDuration * (2.0f - playerSkillFactor);
        
        return Math.max(0.5f, Math.min(2.0f, adjustedDuration));
    }
    
    /**
     * 检测下蹲技巧评分
     * 
     * @param timingAccuracy 时机准确度 (0.0-1.0)
     * @return 技巧评分 (0-100)
     */
    public int calculateDuckingSkillScore(float timingAccuracy) {
        // 基础评分基于时机准确度
        int baseScore = (int) (timingAccuracy * 70);
        
        // 频率奖励：适中的下蹲频率得分更高
        float idealFrequency = 3.0f; // 每分钟3次比较理想
        long sessionDuration = System.currentTimeMillis() - sessionStartTime;
        float sessionMinutes = sessionDuration / 1000f / 60f;
        float actualFrequency = sessionMinutes > 0 ? duckCount / sessionMinutes : 0;
        
        float frequencyScore = 0;
        if (actualFrequency <= idealFrequency) {\n            frequencyScore = actualFrequency / idealFrequency * 30;\n        } else {\n            // 过于频繁的下蹲扣分\n            frequencyScore = 30 - (actualFrequency - idealFrequency) * 5;\n        }\n        \n        int totalScore = (int) Math.max(0, Math.min(100, baseScore + frequencyScore));\n        \n        Log.d(TAG, String.format(\"下蹲技巧评分: %d (时机:%d + 频率:%.1f)\", \n                totalScore, baseScore, frequencyScore));\n        \n        return totalScore;\n    }\n    \n    /**\n     * 提供下蹲改进建议\n     */\n    public void provideDuckingTips() {\n        Log.i(TAG, \"========== 下蹲技巧建议 ==========\");\n        \n        long sessionDuration = System.currentTimeMillis() - sessionStartTime;\n        float sessionMinutes = sessionDuration / 1000f / 60f;\n        float ducksPerMinute = sessionMinutes > 0 ? duckCount / sessionMinutes : 0;\n        \n        if (duckCount == 0) {\n            Log.i(TAG, \"💡 尝试在空中障碍物接近时下蹲躲避\");\n        } else if (ducksPerMinute > 5.0f) {\n            Log.i(TAG, \"💡 不需要过于频繁下蹲，观察障碍物高度\");\n        } else if (ducksPerMinute < 1.0f) {\n            Log.i(TAG, \"💡 适当增加下蹲使用，可以躲避高空障碍物\");\n        } else {\n            Log.i(TAG, \"👍 下蹲使用频率很好！继续保持\");\n        }\n        \n        Log.i(TAG, \"💡 下蹲技巧：提前预判，在障碍物到达前下蹲\");\n        Log.i(TAG, \"💡 组合技：下蹲后可立即跳跃应对连续障碍\");\n        Log.i(TAG, \"===================================\");\n    }\n    \n    /**\n     * 重置统计数据\n     */\n    public void resetStats() {\n        duckCount = 0;\n        totalDuckTime = 0;\n        sessionStartTime = System.currentTimeMillis();\n        Log.i(TAG, \"下蹲统计数据已重置\");\n    }\n    \n    /**\n     * 获取下蹲成功率\n     * \n     * @param successfulDucks 成功躲避的下蹲次数\n     * @return 成功率百分比\n     */\n    public float getDuckingSuccessRate(int successfulDucks) {\n        if (duckCount == 0) {\n            return 0f;\n        }\n        \n        float successRate = (float) successfulDucks / duckCount * 100;\n        Log.d(TAG, String.format(\"下蹲成功率: %.1f%% (%d/%d)\", \n                successRate, successfulDucks, duckCount));\n        \n        return successRate;\n    }\n    \n    // Getter方法\n    public int getDuckCount() { return duckCount; }\n    public float getTotalDuckTime() { return totalDuckTime; }\n    public float getPlayerSkillFactor() { return playerSkillFactor; }\n    public boolean isAdaptiveDurationEnabled() { return adaptiveDurationEnabled; }\n}